package com.example.paypallesson01.v2.subscription;

import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
import com.paypal.api.payments.*;
import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.PayPalRESTException;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * 第一步：创建续费计划
 * @Author: anlu
 * @Date: 2021/07/20
 * @Description: 制定续费计划
 */
public class MakeRenewalPlan {
    private static String clientId = "AcZ2pVjVhgmcL4oaaVlrMtFcYGcYnoGdD-molKMuCSXaV6xZraDqxIFYisZ-1vO8ZlyIPDbNAKtutCnU";
    private static String clientSecret = "ELZSlONq3xB6NB6iDLnOPwsEVv0ZrFRHrTxR_JxUtml1gCHmn3uozul0LG0gDXfWrozdBUM5zhcRyP6z";
    private static String mode = "sandbox";
    protected Plan instance = null;

    @Autowired
    private  APIContext context;

    /**
     * 创建续费计划
     *  https://developer.paypal.com/webapps/developer/docs/api/#create-a-plan
     * @param context
     * @author: anlu
     * @time: 2021/7/20
     */
    public Plan create(APIContext context)throws Exception, IOException{
        //构建计划对象
        Plan plan =  new Plan();
        plan.setName("会员");
        plan.setDescription("我是会员，按月自动续费");
        // 计费方案的类型，FIXED，INFINITE
        plan.setType("FIXED");
        // 付款参数
        PaymentDefinition paymentDefinition = new PaymentDefinition();
        paymentDefinition.setName("定期付款");
        //付款定义的类型。 允许的值：“ TRIAL”，“ REGULAR”）。
        paymentDefinition.setType("REGULAR");
        //提供的付款定义的频率。 允许的值：“WEEK”，“DAY”，“YEAR”，“MONTH”。
        paymentDefinition.setFrequency("MONTH");
        //多久（setFrequency）向用户收取一次费用
        paymentDefinition.setFrequencyInterval("1");
        //收款的周期（次数）,无期限使用“0”
        paymentDefinition.setCycles("12");

        //金额
        Currency currency = new Currency();
        currency.setCurrency("USD");
        // 设置续费的金额是10美金
        currency.setValue("10");
        paymentDefinition.setAmount(currency);

        // 收费模式
        ChargeModels chargeModels = new ChargeModels();

        //收费模式的类型。 允许的值：`SHIPPING`运费，`TAX`税费。
        chargeModels.setType("SHIPPING");
        chargeModels.setAmount(currency);
        List<ChargeModels> chargeModelsList = new ArrayList<ChargeModels>();
        chargeModelsList.add(chargeModels);
        paymentDefinition.setChargeModels(chargeModelsList);

        //付款定义
        List<PaymentDefinition> paymentDefinitionList = new ArrayList<PaymentDefinition>();
        paymentDefinitionList.add(paymentDefinition);
        plan.setPaymentDefinitions(paymentDefinitionList);
        //商家设置
        MerchantPreferences merchantPreferences = new MerchantPreferences();
        merchantPreferences.setSetupFee(currency);
        merchantPreferences.setCancelUrl("https://www.example.com");
        merchantPreferences.setReturnUrl("https://www.example.com");
        //允许的失败尝试总数。默认值为0，表示无数次失败的尝试
        merchantPreferences.setMaxFailAttempts("0");
        //允许在下一个周期中为未结协议金额自动计费。 允许的值：“YES”，“NO”。 默认为“NO”。
        merchantPreferences.setAutoBillAmount("YES");
        //如果在首次付款期间发生故障，应采取的措施。 允许的值："CONTINUE"，"CANCEL"。 默认为"CONTINUE"。
        merchantPreferences.setInitialFailAmountAction("CONTINUE");
        plan.setMerchantPreferences(merchantPreferences);

        this.instance = plan.create(context);
        System.out.println("planId:" + this.instance.getId());
        return this.instance;
    }
    /**
     *  更新续费计划（激活）
     *
     * https://developer.paypal.com/webapps/developer/docs/api/#update-a-plan
     *
     * @return 更新后的计划
     * @throws
     */
    public Plan update(APIContext context) throws Exception, IOException {

        List<Patch> patchRequestList = new ArrayList<Patch>();
        Map<String, String> value = new HashMap<String, String>();
        value.put("state", "ACTIVE");

        Patch patch = new Patch();
        patch.setPath("/");
        patch.setValue(value);
        patch.setOp("replace");
        patchRequestList.add(patch);

        this.instance.update(context, patchRequestList);
        return this.instance;
    }

    /**
     * 查询续费计划
     *
     * https://developer.paypal.com/webapps/developer/docs/api/#retrieve-a-plan
     *
     * @return 查询到的续费计划
     * @throws Exception
     */
    public Plan retrieve(APIContext context) throws Exception {
        return Plan.get(context, this.instance.getId());
    }

    public static void main(String[] args)throws Exception {
        try {
            MakeRenewalPlan subscriptionSample = new MakeRenewalPlan();
            APIContext context = new APIContext(clientId, clientSecret, mode);
            subscriptionSample.create(context);
            System.out.println("create response:\n" + Plan.getLastResponse());
            subscriptionSample.update(context);
            System.out.println("plan updated");
//			subscriptionSample.retrieve(context);
//			System.out.println("retrieve response:\n" + Plan.getLastResponse());
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
        } catch (JsonIOException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (PayPalRESTException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
